/*
 * LoginServlet.java
 *
 * Created on 4 Ноябрь 2006 г., 16:01
 */

package authregistration;

import com.sun.corba.se.spi.protocol.RequestDispatcherDefault;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

import javax.naming.*;

import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.callback.CallbackHandler;


import org.apache.log4j.Logger;

public class LoginServlet extends HttpServlet {
    private static final String CONTENT_TYPE =
            "text/html; charset=windows-1251";
    private Logger log = null;
    //Initialize global variables
    public void init() throws ServletException {
        //Root Loger
        log = Logger.getRootLogger();
        log.info("Logger Started");
    }

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        WebCallBack webcallback = new WebCallBack(request);
        LoginContext lcontext = null;
        ServletContext context = getServletContext();

        boolean loginSuccess = true;
        try{
            lcontext = new LoginContext("ServletGame",webcallback);
            context.log("Our DateSource is working");
            lcontext.login();
        }catch (LoginException lge){
            context.log(lge.getMessage());
            System.out.println(lge.getLocalizedMessage()+lge.getMessage());
            loginSuccess = false;
        }
        response.setContentType(CONTENT_TYPE);

        PrintWriter out = response.getWriter();
        
        RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
        if(!loginSuccess){
            response.setStatus(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
            dispatcher.forward(request,response);
        }else{
            dispatcher = null;
            dispatcher = request.getRequestDispatcher("/iprecordservlet");
            dispatcher.forward(request,response);
        }
        out.close();

    }

    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }

    //Clean up resources
    public void destroy() {
    }
}
